#include "CUdpNetwork.h"

CUdpNetwork* CUdpNetwork::singleton = 0;

CUdpNetwork::CUdpNetwork()
{
    this->udp_socket = new QUdpSocket;
}

CUdpNetwork::~CUdpNetwork()
{
    delete this->udp_socket;
}

CUdpNetwork* CUdpNetwork::get_instance()
{
    if(!singleton)
    {
        singleton = new CUdpNetwork;
    }

    return singleton;
}

// Authentification de la personne sur le GameServer
void CUdpNetwork::connect(QString hostname, quint16 port, MCharacter *m_character)
{
    // Retient l'hostname et le port
    CUdpNetwork::get_instance()->hostname = hostname;
    CUdpNetwork::get_instance()->port = port;

    // Initialise une connexion UDP
    CUdpNetwork::get_instance()->udp_socket->bind(QHostAddress::QHostAddress(hostname), port);

    // Attend que des paquets arrivent
    QObject::connect(CUdpNetwork::get_instance()->udp_socket, SIGNAL(readyRead()),this, SLOT(receive()));

    // Envoie les informations requisent au GameServer (MCharacter)
    CUdpNetwork::get_instance()->send("login");
    CUdpNetwork::get_instance()->send(QString::number(m_character->get_id()));
    CUdpNetwork::get_instance()->send(m_character->get_username());
    CUdpNetwork::get_instance()->send(m_character->get_bonus());
    CUdpNetwork::get_instance()->send(QString::number(m_character->get_exp()));
    CUdpNetwork::get_instance()->send(QString::number(m_character->get_level()));
}

void CUdpNetwork::send(QString message)
{
    QByteArray datagram = message.toLocal8Bit();
    CUdpNetwork::get_instance()->udp_socket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::QHostAddress(CUdpNetwork::get_instance()->hostname), CUdpNetwork::get_instance()->port);
    CUdpNetwork::get_instance()->udp_socket->write(message.toLocal8Bit());
}

QString CUdpNetwork::receive()
{
    while (CUdpNetwork::get_instance()->udp_socket->hasPendingDatagrams())
    {
         QByteArray datagram;
         datagram.resize(CUdpNetwork::get_instance()->udp_socket->pendingDatagramSize());
         QHostAddress *sender = new QHostAddress(CUdpNetwork::get_instance()->hostname);
         CUdpNetwork::get_instance()->udp_socket->readDatagram(datagram.data(), datagram.size(), sender, &CUdpNetwork::get_instance()->port);

         emit is_receiving(QString::fromAscii(datagram.data()));

         delete sender;

         return QString::fromAscii(datagram.data());
     }
}
